package com.kekezu.kppw.utils;

import java.io.File;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.DownloadManager;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Images.ImageColumns;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;

public class StrFormat {
	static public boolean formatStr(String str) {
		if (str != "" && str != null && !str.equals("") && !str.equals("null")) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[^4,\\D])|(17[0,1,7]))\\d{8}$");

		Matcher m = p.matcher(mobiles);

		return m.matches();

	}

	/**
	 * 对字符加星号处理：除前面几位和后面几位外，其他的字符以星号代替
	 * 
	 * @param content
	 *            传入的字符串
	 * @param frontNum
	 *            保留前面字符的位数
	 * @param endNum
	 *            保留后面字符的位数
	 * @return 带星号的字符串
	 */

	public static String getStarString(String content, int frontNum, int endNum) {

		if (frontNum >= content.length() || frontNum < 0) {
			return content;
		}
		if (endNum >= content.length() || endNum < 0) {
			return content;
		}
		if (frontNum + endNum >= content.length()) {
			return content;
		}
		String starStr = "";
		for (int i = 0; i < (content.length() - frontNum - endNum); i++) {
			starStr = starStr + "*";
		}
		return content.substring(0, frontNum)
				+ starStr
				+ content
						.substring(content.length() - endNum, content.length());

	}

	// 将传入时间与当前时间进行对比，是否今天昨天
	public static String getTime(String string) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = null;
		try {
			date = sdf.parse(string);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		String todySDF = "今天 HH:mm";
		String yesterDaySDF = "昨天HH:mm";
		String otherSDF = "MM-dd HH:mm";
		SimpleDateFormat sfd = null;
		String time = "";
		Calendar dateCalendar = Calendar.getInstance();
		dateCalendar.setTime(date);
		Date now = new Date();
		Calendar targetCalendar = Calendar.getInstance();
		targetCalendar.setTime(now);
		targetCalendar.set(Calendar.HOUR_OF_DAY, 0);
		targetCalendar.set(Calendar.MINUTE, 0);
		if (dateCalendar.after(targetCalendar)) {
			sfd = new SimpleDateFormat(todySDF);
			time = sfd.format(date);
			return time;
		} else {
			targetCalendar.add(Calendar.DATE, -1);
			if (dateCalendar.after(targetCalendar)) {
				sfd = new SimpleDateFormat(yesterDaySDF);
				time = sfd.format(date);
				return time;
			}
		}
		sfd = new SimpleDateFormat(otherSDF);
		time = sfd.format(date);
		return time;
	}

	public static String getRealFilePath(Context context, final Uri uri) {
		if (null == uri)
			return null;
		final String scheme = uri.getScheme();
		String data = null;
		if (scheme == null)
			data = uri.getPath();
		else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
			data = uri.getPath();
		} else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
			Cursor cursor = context.getContentResolver().query(uri,
					new String[] { ImageColumns.DATA }, null, null, null);
			if (null != cursor) {
				if (cursor.moveToFirst()) {
					int index = cursor.getColumnIndex(ImageColumns.DATA);
					if (index > -1) {
						data = cursor.getString(index);
					}
				}
				cursor.close();
			}
		}
		return data;
	}

	/**
	 * 解决小米手机上获取图片路径为null的情况
	 * 
	 * @param intent
	 * @return
	 */
	public static Uri geturi(Context context, android.content.Intent intent) {
		Uri uri = intent.getData();
		String type = intent.getType();
		if (uri.getScheme().equals("file") && (type.contains("image/"))) {
			String path = uri.getEncodedPath();
			if (path != null) {
				path = Uri.decode(path);
				ContentResolver cr = context.getContentResolver();
				StringBuffer buff = new StringBuffer();
				buff.append("(").append(Images.ImageColumns.DATA).append("=")
						.append("'" + path + "'").append(")");
				Cursor cur = cr.query(Images.Media.EXTERNAL_CONTENT_URI,
						new String[] { Images.ImageColumns._ID },
						buff.toString(), null, null);
				int index = 0;
				for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
					index = cur.getColumnIndex(Images.ImageColumns._ID);
					// set _id value
					index = cur.getInt(index);
				}
				if (index == 0) {
					// do nothing
				} else {
					Uri uri_temp = Uri
							.parse("content://media/external/images/media/"
									+ index);
					if (uri_temp != null) {
						uri = uri_temp;
					}
				}
			}
		}
		return uri;
	}

	/**
	 * 动态的算出ListView实际高度 动态的算出ListView实际的LayoutParams 最关键的是算出LayoutParams.height
	 */
	static public ViewGroup.LayoutParams getListViewParams(ListView listView) {
		// 通过ListView获取其中的适配器adapter
		ListAdapter listAdapter = listView.getAdapter();

		// 声明默认高度为0
		int totalHeight = 0;
		// 便利ListView所有的item，累加所有item的高度就是ListView的实际高度
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}
		// 将累加获取的totalHeight赋值给LayoutParams的height属性
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		return params;
	}

	/**
	 * 动态的算出GridView实际高度 动态的算出GridView实际的LayoutParams 最关键的是算出LayoutParams.height
	 */
	static public ViewGroup.LayoutParams getListViewParams(GridView gridView) {
		// 通过ListView获取其中的适配器adapter
		ListAdapter listAdapter = gridView.getAdapter();

		// 声明默认高度为0
		int totalHeight = 0;
		// 便利ListView所有的item，累加所有item的高度就是ListView的实际高度
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, gridView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}
		// 将累加获取的totalHeight赋值给LayoutParams的height属性
		ViewGroup.LayoutParams params = gridView.getLayoutParams();
		params.height = totalHeight
				+ (gridView.getHeight() * (listAdapter.getCount() - 1));
		return params;
	}

	// pop全屏
	static public void fitPopupWindowOverStatusBar(PopupWindow popWindow,
			boolean needFullScreen) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			try {
				Field mLayoutInScreen = PopupWindow.class
						.getDeclaredField("mLayoutInScreen");
				mLayoutInScreen.setAccessible(true);
				mLayoutInScreen.set(popWindow, needFullScreen);
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static boolean fileIsExists(String fileName) {
		File f = new File("/kppw/cache/" + fileName);
		if (!f.exists()) {
			return false;
		}
		return true;
	}

	public static void getDownFile(Context context, String path, String fileName) {
		// 创建下载任务,downloadUrl就是下载链接
		DownloadManager.Request request = new DownloadManager.Request(
				Uri.parse(path));
		// 指定下载路径和下载文件名
		request.setDestinationInExternalPublicDir("/kppw/cache/", fileName);
		// 获取下载管理器
		DownloadManager downloadManager = (DownloadManager) context
				.getSystemService(Context.DOWNLOAD_SERVICE);
		// 将下载任务加入下载队列，否则不会进行下载
		downloadManager.enqueue(request);
	}

}
